<?php
namespace app\api\controller;

use think\Controller;
use app\common\model\User as UserModel;

class User extends Controller
{
    /**
     * 用户登录
     * @param string $username 用户名
     * @param string $password 密码
     * @return json
     */
    public function login()
    {
        if (!$this->request->isPost()) {
            return json(['code' => 0, 'msg' => '非法请求']);
        }

        $data = $this->request->post();
        $validate = validate('User');
        if (!$validate->scene('login')->check($data)) {
            return json(['code' => 0, 'msg' => $validate->getError()]);
        }

        $user = UserModel::where('username', $data['username'])->find();
        if (!$user || !password_verify($data['password'], $user->password)) {
            return json(['code' => 0, 'msg' => '用户名或密码错误']);
        }

        session('user_id', $user->id);
        return json(['code' => 1, 'msg' => '登录成功', 'data' => $user->visible(['id', 'username', 'nickname', 'avatar'])]);
    }

    /**
     * 用户注册
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $nickname 昵称
     * @return json
     */
    public function register()
    {
        if (!$this->request->isPost()) {
            return json(['code' => 0, 'msg' => '非法请求']);
        }

        $data = $this->request->post();
        $validate = validate('User');
        if (!$validate->scene('register')->check($data)) {
            return json(['code' => 0, 'msg' => $validate->getError()]);
        }

        $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        
        if (UserModel::create($data)) {
            return json(['code' => 1, 'msg' => '注册成功']);
        }
        return json(['code' => 0, 'msg' => '注册失败']);
    }

    /**
     * 获取用户信息
     * @return json
     */
    public function info()
    {
        $user_id = session('user_id');
        if (!$user_id) {
            return json(['code' => 0, 'msg' => '未登录']);
        }

        $user = UserModel::find($user_id);
        return json(['code' => 1, 'data' => $user->visible(['id', 'username', 'nickname', 'avatar'])]);
    }

    /**
     * 更新用户信息
     * @param string $nickname 昵称
     * @param string $avatar 头像
     * @return json
     */
    public function update()
    {
        if (!$this->request->isPost()) {
            return json(['code' => 0, 'msg' => '非法请求']);
        }

        $user_id = session('user_id');
        if (!$user_id) {
            return json(['code' => 0, 'msg' => '未登录']);
        }

        $data = $this->request->post();
        $validate = validate('User');
        if (!$validate->scene('update')->check($data)) {
            return json(['code' => 0, 'msg' => $validate->getError()]);
        }

        $user = UserModel::find($user_id);
        if ($user->save($data)) {
            return json(['code' => 1, 'msg' => '更新成功']);
        }
        return json(['code' => 0, 'msg' => '更新失败']);
    }
}